//
//  LZYSelectPhotoView.m
//  Supervisor
//
//  Created by 小宇 on 2017/5/18.
//  Copyright © 2017年 北京怀教网络科技股份有限公司. All rights reserved.
//

#import "LZYSelectPhotoView.h"
#import "TZImagePickerController.h"
#import "UIImageView+WebCache.h"
#import "MWPhotoBrowser.h"
#import "LZYPhotoManager.h"
#import "LZYPhotoCell.h"
#import "LZYShowMsg.h"
#import "LZYAlertController.h"
#import "UIView+Frame.h"
#import "NSString+LZYNSString.h"
#import "Tool.h"
@interface LZYSelectPhotoView ()<UICollectionViewDelegate, UICollectionViewDataSource, TZImagePickerControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, MWPhotoBrowserDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, copy) LZYMediaHeightBlock block;

@property (nonatomic, copy) LZYSelectMediaBackBlock backBlock;

/** 总的媒体数组 */
@property (nonatomic, strong) NSMutableArray *mediaArray;

/** 记录从相册中已选的Image Asset */
@property (nonatomic, strong) NSMutableArray *selectedImageAssets;

/** 记录从相册中已选的Image model */
@property (nonatomic, strong) NSMutableArray *selectedImageModels;

/** 记录从相册中已选的Video model*/
@property (nonatomic, strong) NSMutableArray *selectedVideoModels;

/** MWPhoto对象数组 */
@property (nonatomic, strong) NSMutableArray *photos;

@end

@implementation LZYSelectPhotoView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self _setup];
    }
    return self;
}

- (void)_setup {
    _mediaArray = [NSMutableArray array];
    _preShowMedias = [NSMutableArray array];
    _selectedImageAssets = [NSMutableArray array];
    _selectedVideoModels = [NSMutableArray array];
    _selectedImageModels = [NSMutableArray array];
    _maxImageSelected = 9;
    _backgroundColor = [UIColor whiteColor];
    [self configureCollectionView];
}

- (void)configureCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(self.width/4, self.width/4);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:layout];
    [_collectionView registerClass:[LZYPhotoCell class] forCellWithReuseIdentifier:NSStringFromClass([LZYPhotoCell class])];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = _backgroundColor;
    [self addSubview:_collectionView];
}

#pragma mark - getter

- (UIViewController *)rootViewController {
    if (!_rootViewController) {
        _rootViewController = [self getCurrentVC];
    }
    return _rootViewController;
}

- (void)setShowAddButton:(BOOL)showAddButton {
    _showAddButton = showAddButton;
    if (_mediaArray.count > 3 || _mediaArray.count == 0) {
        [self layoutCollection];
    }
}

- (void)setPreShowMedias:(NSArray *)preShowMedias {
    
    _preShowMedias = preShowMedias;
    NSMutableArray *temp = [NSMutableArray array];
    if (preShowMedias.count > 0 && [preShowMedias[0] isKindOfClass:[NSDictionary class]]) {
        for (NSDictionary *object in preShowMedias) {
            LZYPhotoModel *model = [LZYPhotoModel new];
            model.imageUrlString = object[@"filepath"];
            model.name = object[@"filename"];
            [temp addObject:model];
        }
    }else if (preShowMedias.count > 0 && [preShowMedias[0] isKindOfClass:[UIImage class]]){
        for (UIImage *object in preShowMedias) {
            LZYPhotoModel *model = [LZYPhotoModel new];
            model.image = object;
            [temp addObject:model];
        }
    }else if (preShowMedias.count > 0 && [preShowMedias[0] isKindOfClass:[LZYPhotoModel class]]){
        temp = [NSMutableArray arrayWithArray:preShowMedias];
    }else{
        [self.mediaArray removeAllObjects];
        [self.selectedImageAssets removeAllObjects];
        [self.selectedImageModels removeAllObjects];
        [self.selectedVideoModels removeAllObjects];
        [self layoutCollectionNoBlock];
    }
    if (temp.count > 0) {
        _mediaArray = temp;
        [self layoutCollectionNoBlock];
    }
}



#pragma mark - public method

- (void)observeViewHeight:(LZYMediaHeightBlock)value {
    _block = value;
    //预防先加载数据源的情况
    if (_mediaArray.count > 3) {
        _block(_collectionView.height);
    }
}

- (void)observeSelectedMediaArray: (LZYSelectMediaBackBlock)backBlock {
    _backBlock = backBlock;
}

+ (CGFloat)defaultViewHeight {
    return kScreenWidthRatio*70;
}

- (void)reload {
    [self.collectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _showAddButton ? _mediaArray.count + 1 : _mediaArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LZYPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LZYPhotoCell class]) forIndexPath:indexPath];
    if (indexPath.item == _mediaArray.count) {
        cell.icon.image = [UIImage imageNamed:@"AddPhoto"];
        cell.videoImageView.hidden = YES;
        cell.deleteButton.hidden = YES;
    }else{
        LZYPhotoModel *model = _mediaArray[indexPath.row];
        if (!model.isVideo && model.imageUrlString) {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:model.imageUrlString] placeholderImage:nil];
        }else {
            cell.icon.image = model.image;
        }
        cell.deleteButton.hidden = self.hideDeleteButton;
        __weak typeof(self)weakSelf = self;
        //删除图片
        [cell setACMediaClickDeleteButton:^{
            LZYPhotoModel *model = weakSelf.mediaArray[indexPath.row];
            if ([weakSelf.selectedImageModels containsObject:model]) {
                    for (NSInteger idx =0; idx < weakSelf.selectedImageModels.count; idx++) {
                        if (weakSelf.selectedImageModels[idx] == model) {
                            [weakSelf.selectedImageAssets removeObjectAtIndex:idx];
                            [weakSelf.selectedImageModels removeObject:model];
                            break;
                        }
                    }
            }
            //总数据源中删除对应项
            [weakSelf.mediaArray removeObjectAtIndex:indexPath.row];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self layoutCollection];
            });
        }];
    }
    return cell;
}

#pragma mark - collection view delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _mediaArray.count && _mediaArray.count >= _maxImageSelected) {
        [LZYShowMsg showBottomWithText:[NSString stringWithFormat:@"最多只能选择%ld张",(long)_maxImageSelected]];
        return;
    }
    __weak typeof(self) weakSelf = self;
    //点击的是添加媒体的按钮
    if (indexPath.row == _mediaArray.count) {
        //发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"mediaAddPhoto" object:nil];
        LZYAlertController *alert = [[LZYAlertController alloc] initWithActionSheetTitles:@[@"相册", @"相机"] cancelTitle:@"取消"];
        [alert clickActionButton:^(NSInteger index) {
            if (index == 0) {
                [weakSelf openAlbum];
            }else {
                [weakSelf openCamera];
            }
        }];
            [alert show];
    }
    //展示媒体
    else {
        _photos = [NSMutableArray array];
        MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
        browser.displayActionButton = YES;//分享按钮,默认是
        browser.displayNavArrows = YES;//左右分页切换,默认否
        browser.displaySelectionButtons = NO;//是否显示选择按钮在图片上,默认否
        browser.alwaysShowControls = YES;//控制条件控件 是否显示,默认否
        browser.zoomPhotosToFill = YES;//是否全屏,默认是
        browser.enableGrid = YES;//是否允许用网格查看所有图片,默认是
        browser.startOnGrid = NO;//是否第一张,默认否
        browser.delayToHideElements = 0.5;
        [browser showNextPhotoAnimated:YES];
        [browser showPreviousPhotoAnimated:YES];
        for (LZYPhotoModel *model in _mediaArray) {
            MWPhoto *photo;
            if (model.image == nil && ![NSString isEmpty:model.imageUrlString]) {
                photo = [MWPhoto photoWithURL:[NSURL URLWithString:model.imageUrlString]];
            }else{
                photo = [MWPhoto photoWithImage:model.image];
            }
            photo.caption = model.name;
            [_photos addObject:photo];
        }
        [browser setCurrentPhotoIndex:indexPath.row];
        [[self getCurrentVC].navigationController pushViewController:browser animated:YES];
    }
}

#pragma mark - <MWPhotoBrowserDelegate>

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count) {
        return [self.photos objectAtIndex:index];
    }
    return nil;
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser{
    [Tool navigationController:self].navigationBarHidden = NO;
}

#pragma mark - 布局

///重新布局collectionview
- (void)layoutCollection {
    NSInteger allImageCount = _showAddButton ? _mediaArray.count + 1 : _mediaArray.count;
    NSInteger maxRow = (allImageCount - 1) / 4 + 1;
    _collectionView.height = allImageCount == 0 ? 0 : maxRow * Main_Screen_Width/4;
    self.height = _collectionView.height;
    //block回调
    !_block ?  : _block(_collectionView.height);
    !_backBlock ?  : _backBlock(_mediaArray);
    [_collectionView reloadData];
}

///重新布局collectionview
- (void)layoutCollectionNoBlock {
    NSInteger allImageCount = _showAddButton ? _mediaArray.count + 1 : _mediaArray.count;
    NSInteger maxRow = (allImageCount - 1) / 4 + 1;
    _collectionView.height = allImageCount == 0 ? 0 : maxRow * Main_Screen_Width/4;
    self.height = _collectionView.height;
    [_collectionView reloadData];
}

- (CGFloat)getCollectionViewHeightWithPhotoCount:(NSInteger)photoCount{
    NSInteger allImageCount = _showAddButton ? photoCount + 1 : photoCount;
    NSInteger maxRow = (allImageCount - 1) / 4 + 1;
    return allImageCount == 0 ? 0 : maxRow * Main_Screen_Width/4;
}

#pragma mark - actions

/** 相册 */
- (void)openAlbum {
    NSInteger count = 0;
    count = _maxImageSelected - (_mediaArray.count - _selectedImageModels.count);
    TZImagePickerController *imagePickController = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
    [self configureTZNaviBar:imagePickController];
    //是否 在相册中显示拍照按钮
    imagePickController.allowTakePicture = NO;
    //是否可以选择显示原图
    imagePickController.allowPickingOriginalPhoto = NO;
    //是否 在相册中可以选择视频
    imagePickController.allowPickingVideo = NO;
    imagePickController.selectedAssets = _selectedImageAssets;
    [self.rootViewController presentViewController:imagePickController animated:YES completion:nil];
}

/** 相机 */
- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = NO;
        picker.sourceType = sourceType;
        [self.rootViewController presentViewController:picker animated:YES completion:nil];
    }else{
        [LZYShowMsg showBottomWithText:@"该设备不支持拍照"];
    }
}

#pragma mark - TZImagePickerController Delegate

//处理从相册单选或多选的照片
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    
    if ([_selectedImageAssets isEqualToArray: assets]) {
        return;
    }
    //每次回传的都是所有的asset 所以要初始化赋值
    _selectedImageAssets = [NSMutableArray arrayWithArray:assets];
    
    NSMutableArray *models = [NSMutableArray array];
    //2次选取照片公共存在的图片
    NSMutableArray *temp = [NSMutableArray array];
    NSMutableArray *temp2 = [NSMutableArray array];
    for (NSInteger index = 0; index < assets.count; index++) {
        PHAsset *asset = assets[index];
        [[LZYPhotoManager manager] getMediaInfoFromAsset:asset completion:^(NSString *name, id pathData) {
            LZYPhotoModel *model = [[LZYPhotoModel alloc] init];
            model.name = name;
            model.uploadType = pathData;
            model.image = photos[index];
            
//            //区分gif
//            if ([NSString isGifWithImageData:pathData]) {
//                model.image = [UIImage ac_setGifWithData:pathData];
//            }
            __weak typeof(self)weakSelf = self;
            //用数组是否包含来判断是不成功的。。。
            for (LZYPhotoModel *md in weakSelf.selectedImageModels) {
                if ([md.name isEqualToString:model.name]) {
                    [temp addObject:md];
                    [temp2 addObject:model];
                    break;
                }
            }
            [models addObject:model];
            if (index == assets.count - 1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //删除公共存在的，剩下的就是已经不存在的
                    [weakSelf.selectedImageModels removeObjectsInArray:temp];
                    //总媒体数组删先除掉不存在，这样不会影响排列的先后顺序
                    [weakSelf.mediaArray removeObjectsInArray:weakSelf.selectedImageModels];
                    //将这次选择的进行赋值，深复制
                    weakSelf.selectedImageModels = [models mutableCopy];
                    //这次选择的删除公共存在的，剩下的就是新添加的
                    [models removeObjectsInArray:temp2];
                    //总媒体数组中在后面添加新数据
                    [weakSelf.mediaArray addObjectsFromArray:models];
                    [self layoutCollection];
                });
            }
        }];
    }
}

#pragma mark - UIImagePickerController Delegate
///拍照
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //媒体类型
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //原图URL
    NSURL *imageAssetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    
    if ([mediaType isEqualToString:@"public.image"]) {
        
        UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
        //如果 picker 没有设置可编辑，那么image 为 nil
        if (image == nil) {
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        
        PHAsset *asset;
        //拍照没有原图 所以 imageAssetURL 为nil
        if (imageAssetURL) {
            PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[imageAssetURL] options:nil];
            asset = [result firstObject];
        }
        __weak typeof(self)weakSelf = self;
        [[LZYPhotoManager manager] getImageInfoFromImage:image PHAsset:asset completion:^(NSString *name, NSData *data) {
            LZYPhotoModel *model = [[LZYPhotoModel alloc] init];
            model.image = image;
            model.name = name;
            model.uploadType = data;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.mediaArray addObject:model];
                [self layoutCollection];
            });
        }];
    }
}

- (NSArray *)getAllPhotos{
    NSMutableArray *imgArr = [NSMutableArray arrayWithArray:self.mediaArray];
    return imgArr;
}

- (NSArray *)getLocalPhotos{
    NSMutableArray *imgArr = [NSMutableArray arrayWithCapacity:self.mediaArray.count];
    for (LZYPhotoModel *model in self.mediaArray) {
        if (model.image != nil && [NSString isEmpty:model.imageUrlString]) {
            [imgArr addObject:model.image];
        }
    }
    return imgArr;
}

- (NSArray *)getFilePathPhotos{
    NSMutableArray *imgArr = [NSMutableArray arrayWithCapacity:self.mediaArray.count];
    for (LZYPhotoModel *model in self.mediaArray) {
        if (model.image != nil && [NSString isEmpty:model.imageUrlString]) {
            [imgArr addObject:model.uploadType];
        }
    }
    return imgArr;
}

- (NSArray *)getUrlPhotos{
    NSMutableArray *imgArr = [NSMutableArray arrayWithCapacity:self.mediaArray.count];
    for (LZYPhotoModel *model in self.mediaArray) {
        if (model.image == nil && ![NSString isEmpty:model.imageUrlString]) {
            [imgArr addObject:model];
        }
    }
    return imgArr;
}

- (void)setHideDeletebutton{
    self.hideDeleteButton = YES;
    [self.collectionView reloadData];
}

- (void)setShowDeletebutton{
    self.hideDeleteButton = NO;
    [self.collectionView reloadData];
}

///配置 TZImagePickerController 导航栏属性
- (void)configureTZNaviBar: (TZImagePickerController *)pick {
    pick.naviBgColor = [UIColor whiteColor];
    pick.naviTitleColor = [UIColor blueColor];
}

//有时候获取不到
- (UIViewController *)getCurrentVC {
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}

@end
